package com.aw.guiguzi.module.common.presenters

import com.aw.baselib.base.AwBaseApplication
import com.aw.baselib.base.AwCommonPresenter
import com.aw.baselib.net.callback.AwApiCallback
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwFileUtil
import com.aw.baselib.util.AwLog
import com.aw.baselib.util.download.AwFileDownloadUtil
import com.aw.baselib.util.download.DownloadResBean
import com.aw.guiguzi.base.MyApp
import com.aw.guiguzi.bean.UserInfoBean
import com.aw.guiguzi.constants.MyConstant
import com.aw.guiguzi.event.EventRefreshTransactionDataType
import com.aw.guiguzi.module.common.views.MainView
import com.aw.guiguzi.net.observers.NetObCommon
import com.aw.guiguzi.util.AppCacheUtil
import com.aw.guiguzi.util.AppUserUtil.saveUser
import com.aw.guiguzi.util.AppUserUtil.userRemark
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * @author : hzw
 */
class MainPresent(private val mView: MainView.View) : AwCommonPresenter(), MainView.Presenter {
    override fun getUserInfo() {
        addIOSubscription(
            NetObCommon.getUserInfo(),
            object : AwApiCallback<UserInfoBean?>(mView, false, true) {
                override fun onSuccess(result: UserInfoBean?) {
                    AwLog.d("Main getUserInfo: $result")
                    saveUser(result)
                    getUserDetail(result?.id)
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                    AwLog.d("Main getUserInfo onFail code: $code ,msg: $msg")
                }
            })
    }

    override fun uploadFile(filePath: String?) {
        AwLog.d("upload path: $filePath")
        val file = File(filePath)
        if (!file.exists()) {
            AwLog.d("Main upload return file not exist")
            return
        }
        addIOSubscription<Any>(
            NetObCommon.uploadFile(filePath),
            object : AwApiCallback<Any?>(mView, false, true) {
                override fun onSuccess(result: Any?) {
                    AwLog.d("Main upload success: $result")
                    AwFileUtil.deleteFile(file.absoluteFile)
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                    AwLog.d("Main upload onFail code: $code ,msg: $msg")
                }
            })
    }

    override fun getMsgUnreadCount() {
        addIOSubscription(
            NetObCommon.getMsgUnreadCount(),
            object : AwApiCallback<String?>(mView, false, true) {
                override fun onSuccess(result: String?) {
                    mView.getMsgUnreadCountSuccess(result)
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                }
            })
    }

    fun getUserDetail(id: String?) {
        addIOSubscription(
            NetObCommon.getUserDetail(id),
            object : AwApiCallback<UserInfoBean?>(mView, false, true) {
                override fun onSuccess(result: UserInfoBean?) {
                    userRemark = result?.remark
                    if (!AwDataUtil.isEmpty(result?.remark)) {
                        if (AwDataUtil.isEmpty(AppCacheUtil.getTransactionFileUrl()) || AppCacheUtil.getTransactionFileUrl() != result?.remark) {
                            AwLog.d("交易配置文件需下载")
                            AppCacheUtil.setTransactionFileUrl(result?.remark)
                            downloadFile(result?.remark)
                        } else {
                            val file =
                                File(AwBaseApplication.getInstance().externalCacheDir.toString() + File.separator + "downloadRes")
                            if (!file.exists()) file.mkdirs()
                            var downloadResFile: File? = null
                            try {
                                downloadResFile = File(file, MyConstant.DEFAULT_TRANSACTION_TXT)
                                if (!downloadResFile.exists()) {
                                    AwLog.d("交易配置文件不存在, 重新下载")
                                    AppCacheUtil.setTransactionFileUrl(result?.remark)
                                    downloadFile(result?.remark)
                                    return
                                }
                                AwLog.d("交易配置文件已存在, 重新下载")
                                MyApp.transactionData =
                                    AwFileUtil.loadFromSDFile(downloadResFile.absolutePath)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                }
            })
    }

    private fun downloadFile(filePath: String?) {
        val downloadResBeanList: MutableList<DownloadResBean> = ArrayList()
        val downloadResBean = DownloadResBean()
        downloadResBean.fileName = MyConstant.DEFAULT_TRANSACTION_TXT
        downloadResBean.url = filePath
        val file = File(downloadResBean.path)
        if (file.exists()) {
            file.delete()
        }
        downloadResBeanList.add(downloadResBean)
        AwFileDownloadUtil.startDownload(
            downloadResBeanList,
            true,
            object : FileDownloadListener() {
                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    AwLog.d("Main downloadFile pending....")
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    AwLog.d("Main downloadFile progress....")
                }

                override fun completed(task: BaseDownloadTask) {
                    AwLog.d("Main downloadFile completed....")
                    //读取...
                    MyApp.transactionData = AwFileUtil.loadFromSDFile(downloadResBean.path)
                    AwLog.d("Main MyApp.transactionData: " + MyApp.transactionData)
                    EventBus.getDefault().postSticky(EventRefreshTransactionDataType(null))
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    AwLog.d("Main downloadFile paused....")
                }

                override fun error(task: BaseDownloadTask, e: Throwable) {
                    AwLog.d("Main downloadFile error....")
                }

                override fun warn(task: BaseDownloadTask) {
                    AwLog.d("Main downloadFile warn....")
                }
            })
    }
}